<template>
	<view class="">
		<head-navbar :back="true">
			<view>我的订单</view>
		</head-navbar>
		<view class="content">
			<view class="navbar">
				<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{current: tabCurrentIndex === index,show: index==2}"
				 @click="tabClick(index)">
					{{item.text}}
				</view>
			</view>

			<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab" :style="{height:getTabbarContentHeight}">
				<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
					<scroll-view class="list-scroll-content" scroll-y >
						<!-- 空白页 -->
						<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>
			
						<!-- 订单列表 -->
						<view v-for="(item,index) in tabItem.orderList" :key="index" class="order-item" 
						@click="toPage(0,'/pages/order/orderDeatil/orderDeatil?id='+item.orderId+'&state='+item.status)"
						v-if="item.status != 8"
						>
							<view class="i-top b-b">
								<text class="time"><text>订单号</text>{{item.orderNo}}</text>
							<!-- 	<text class="type"><text>订单类型：</text>{{item.orderTypeName}}</text> -->
								<text class="state"> {{item.statusName}}</text>
							</view>
			
							<!-- <view class="goods-box-single" v-for="(goodsItem, goodsIndex) in item.goodsList" :key="goodsIndex"> -->
							<view class="goods-box-single">
								<image class="goods-img" :src="item.goodsSpecsImg" mode="aspectFill"></image>
								<view class="right">
									<text class="title clamp">{{item.goodsName}}</text>
									<view class="attr-box">
										<view class="left">
											<text>规格：</text> {{item.goodsSpecsName}}
										</view>
										<view class="">
											x {{item.quantity}}
										</view>
									</view>
									<view class="price">
										<view>
											<text class="left">实付款:</text>
											<text class="rightTxt">￥{{item.paymentAmount}}</text>
										</view>
									</view>
									<view class="btnBox" v-if="item.status == 2">
										<!-- <view class="btn" @click.stop="UseOrder(item.orderId)">申请自用</view> -->
										<!-- <view class="btn" @click.stop="cancelBtn(item.orderId,item.quantity)">取消订单</view> -->
										<!-- <view class="btn" @click.stop="consignment(item.orderId)">一键预售</view> -->
									</view>
									<view class="btnBox" v-if="item.status == 3" style="justify-content: flex-end;">
										<!-- <view class="btn" @click.stop="cancelBtn(item.orderId,item.quantity)">取消订单</view> -->
									</view>
								</view>
							</view>
							<view class="action-box b-t" v-if="item.status == 1">
								<button class="action-btn recom" @click.stop="cancelBtn(item)">取消订单</button>
								<button class="action-btn recom" @click.stop ="toPay(item)">立即支付</button>
							</view>
							<view class="action-box b-t" v-if="item.status == 2">
								<!-- <button class="action-btn" @click="cancelOrder(item)">取消订单</button> -->
							</view>
							<view class="action-box b-t" v-if="item.status == 3">
								<!-- <button class="action-btn" @click="cancelOrder(item)">取消订单</button> -->
							</view>
							<view class="action-box b-t" v-if="item.status == 4">
								<!-- <button class="action-btn recom" @click="cancelOrder(item)">查看物流</button> -->
								<button class="action-btn recom" @click.stop="comfimOrder(item)">确认收货</button>
							</view>
							<!-- <view class="action-box b-t" v-if="item.status == 5">
								<button class="action-btn jifen" @click="cancelOrder(item)" >获赠奖励</button>
							</view> -->
							<view class="action-box b-t" v-if="item.status == 6">
								<!-- <button class="action-btn" @click.stop.prevent="toPage(0,'/pages/evaluation/evaluation?id='+item.id)">去评价</button> -->
							</view>
						</view>
			
						<uni-load-more :status="tabItem.loadingType"></uni-load-more>
			
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<pwd-popup ref="pwdPopup" @sendData="selfUseOrder"></pwd-popup>
		<tfgg-verify @result='verifyResult' ref="verifyElement"></tfgg-verify>
		<u-popup v-model="popupshow" mode="center">
			<view class="yt-list">
				<view class="yt-list-cell b-b" @click="payType = 1">
					<view class="cell-tit clamp">
						<image src="../../static/img/hongbao.png" mode=""></image>
						<text class="cell-tit clamp">支付宝</text>
					</view>
					<image src="../../static/img/xuanzhong1.png" mode="" v-if="payType == 1"></image>
					<image src="../../static/img/xuanzhong2.png" mode="" v-else></image>
				</view>
				<view class="yt-list-cell b-b" @click="payType = 3">
					<view class="cell-tit clamp">
						<image src="../../static/img/doudou.png" mode=""></image>
						<text class="cell-tit clamp">余额</text>
					</view>
					<image src="../../static/img/xuanzhong1.png" mode="" v-if="payType == 3"></image>
					<image src="../../static/img/xuanzhong2.png" mode="" v-else></image>
				</view>
				<view class="yt-list-cell b-b" @click="payType = 5">
					<view class="cell-tit clamp">
						<image src="../../static/img/money.png" mode=""></image>
						<text class="cell-tit clamp">闲豆</text>
					</view>
					<image src="../../static/img/xuanzhong1.png" mode=" " v-if="payType == 5"></image>
					<image src="../../static/img/xuanzhong2.png" mode="" v-else></image>
				</view>
				<!-- <view class="yt-list-cell b-b" @click="payType = 4">
					<view class="cell-tit clamp">
						<text class="iconfont icon-USDT usdt"></text>
						<text class="cell-tit clamp">USDT</text>
					</view>
					<image src="../../static/img/xuanzhong1.png" mode="" v-if="payType == 4"></image>
					<image src="../../static/img/xuanzhong2.png" mode="" v-else></image>
				</view> -->
				<view class="yt-list-cell b-b" style="justify-content: flex-end;">
					<u-button type="success" size="mini" @click="goPwd">确定</u-button>				
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import tfggVerify from "@/components/tfgg-verify/tfgg-verify.vue";
	import empty from "@/components/empty";
	import * as api from "@/api/order/index.js";
	// import Json from '@/Json';
	export default {
		components: {
			uniLoadMore,
			empty,
			tfggVerify
		},
		data() {
			return {
				payType:1,
				popupshow:false,
				tabCurrentIndex: 0,
				orderList: [],
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						orderList: []
					},
					{
						state: 1,
						text: '待付款',
						loadingType: 'more',
						orderList: []
					},
					{
						state: 2,
						text: '待处理',
						loadingType: 'more',
						orderList: []
					},
					{
						state: 3,
						text: '待发货',
						loadingType: 'more',
						orderList: []
					},
					{
						state: 4,
						text: '待收货',
						loadingType: 'more',
						orderList: []
					},
					
					{
						state: 5,
						text: '完成',
						loadingType: 'more',
						orderList: []
					}
				],
				pageSize:20,
				pageNum:1,
				orderId:''
			};
		},
		computed: {
			// 获取tabbar内容高度=设备可视区高度-手机头部状态栏高度-APP头部导航栏高度(44)-底部菜单高度（50）-搜索框高度（35）-tabbarTitle高度（40）-安全距离（20）
			getTabbarContentHeight() {
				return this.globalData.systemInfo.windowHeight - this.globalData.systemInfo.statusBarHeight - 44  - 40 - 20 + 'px'
			}
		},
		onLoad(options) {
			// this.getOrderList();
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			this.tabCurrentIndex = +options.state;
		},
		onShow() {
			// #ifndef MP
			this.getOrderList(this.tabCurrentIndex)
			// this.loadData(options.state)
			// #endif
			// #ifdef MP
			if (this.tabCurrentIndex == 0) {
				// this.loadData()
				this.getOrderList();
			}
			// #endif
			
		},
		methods: {
			/* 校验结果回调函数 */
			verifyResult(res){
				if(res){
					this.$refs.verifyElement.reset();//校验成功重置插件
					uni.showLoading({
					    title: '加载中'
					});
					this.popupshow = true;
					
					uni.hideLoading()
				}
			},
			goPwd() {
				this.popupshow = false;
				if(this.payType == 1) {
					this.selfUseOrder();
				}else{
					this.$refs.pwdPopup.show();
				}
				
			},
			//取消订单
			async cancelBtn(item) {
				try {
					console.log(item)
					let params = {
						orderId: item.orderId,
						quantity: item.quantity
					}
					const ret = await api.cancelOrder(params);
					uni.showToast({
						title:"取消成功",
						icon:'none'
					})
					if(this.tabCurrentIndex == 0) {
						this.getOrderList('');
					}else{
						this.getOrderList(this.tabCurrentIndex)
					}
				} catch (error) {
				}
			},
			async comfimOrder(item) {
				try {
					let params = {
						orderId: item.orderId
					}
					const ret = await api.receiptOrder(params);
					uni.showToast({
						title:"成功确认收货",
						icon:'none'
					})
					if(this.tabCurrentIndex == 0) {
						this.getOrderList('');
					}else{
						this.getOrderList(this.tabCurrentIndex)
					}
				} catch (error) {
				}
			},
			toPay(item) {
				uni.showLoading({
					title: '去支付中...'
				})
				api.toPay({
					orderId: item.orderId
				}).then(res => {
					uni.hideLoading()
					uni.setStorageSync('orderList', res.data.obj)
					uni.navigateTo({
						url:'/pages/order/createOrder?orderType=3&orderId=' + item.orderId +'&price=' + (item.quantity*item.unitPrice)+'&freight='+item.freight
					})
				}).catch(err => {
					uni.hideLoading()
				})
			},
			UseOrder(orderId) {
				this.$refs.verifyElement.show();
				this.orderId = orderId;
				// this.selfUseOrder();
			},
			async selfUseOrder(res){
				let data = res;
				uni.showLoading({
				    title: '支付中'
				});
				try {
					let params = {
						orderId:this.orderId,
						payType:this.payType,
						tradePwd:data
					}
					const ret  = await api.selfUseOrder(params);
					if(this.payType == 1) {
						uni.requestPayment({
						    provider: 'alipay',
						    orderInfo: ret.data.obj, //微信、支付宝订单数据
						    success: function (res) {
						        console.log('success:' + JSON.stringify(res));
								setTimeout(function(){
									uni.navigateTo({
										url: '/pages/order/payScuess'
									})
								},500)
						    },
						    fail: function (err) {
						       uni.showToast({
						       	   title:'支付失败',
								   icon:'none'
						       })
						    }
						});
					}else{
						uni.navigateTo({
							url:'/pages/order/payScuess'
						})
					}
				}catch(error) {
					console.log(error)
				}
			},
			// async cancelBtn(orderId,quantity) {
			// 	try {
			// 		let params = {
			// 			orderId:orderId,
			// 			quantity:quantity
			// 		}
			// 		const ret  = await api.cancelOrder(params);
			// 		console.log(ret)
			// 		if(this.tabCurrentIndex == 0) {
			// 			this.getOrderList('');
			// 		}else{
			// 			this.getOrderList(this.tabCurrentIndex)
			// 		}
			// 	}catch(error) {
			// 		console.log(error)
			// 		if(this.tabCurrentIndex == 0) {
			// 			this.getOrderList('');
			// 		}else{
			// 			this.getOrderList(this.tabCurrentIndex)
			// 		}
			// 	}
			// },
			async consignment(orderId){
				try {
					let params = {
						orderId:orderId
					}
					const ret  = await api.consignmentOrder(params);
					this.utils.toast('预售成功');
					console.log(ret)
					if(this.tabCurrentIndex == 0) {
						this.getOrderList('');
					}else{
						this.getOrderList(this.tabCurrentIndex)
					}
				}catch(error) {
					console.log(error)
					if(this.tabCurrentIndex == 0) {
						this.getOrderList('');
					}else{
						this.getOrderList(this.tabCurrentIndex)
					}
				}
			},
			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.getOrderList();
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
			},

			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#fa436a';
				switch (+state) {
					case 1:
						stateTip = '待付款';
						break;
					case 2:
						stateTip = '待处理';
						break;
					case 3:
						stateTip = '待发货';
						break;
					case 4:
						stateTip = '待收货';
						break;
					case 5:
						stateTip = '完成';
						break;
					case 6:
						stateTip = '取消';
						break;
					case 7:
						stateTip = '关闭';
						break;
					case 8:
						stateTip = '预售中';
						break;
						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
		
			async getOrderList(source){
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;
				navItem.loadingType = 'loading';
				this.navList[index].orderList = [];
				try{
					let parmas = {
						orderType:'',
						status:index,
						pageSize:20,
						pageNum:1
					}
					index == 0 ? parmas.status = '' : parmas.status = index;
					const ret = await api.getOrderList(parmas);
					let orderList = ret.data.obj;
					let stateTip = this.orderStateExp(index).stateTip
					this.navList[index].orderList = orderList
					this.navList[index].orderList.forEach(e=>{
						
						e.stateTip = this.orderStateExp(e.status).stateTip;
					})
					navItem.loadingType = 'noMore';
					//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
					// this.$set(navItem, 'loaded', true);
					
					//判断是否还有数据， 有改为 more， 没有改为noMore 
					// navItem.loadingType = 'more';
				}catch(err){}
			}
		},
	}
</script>

<style lang="scss">
@import './order.scss';
</style>
